import React, { Component } from 'react';
import { Button, Modal, Form, Alert, Popover, Tabs, Table } from 'antd';
import '@/assets/css/settings';
import * as ProductionOrderService from '../../../axios/ProductionOrder'
import * as productionLayoutListService from '../../../axios/productionLayoutList'
import { BasicLayoutSearch } from '../../../components/BasicLayout';
import { openModalMessage, compareString } from '../../../components/TableCustomize'
import { workStatusList } from '../../../utils/global';
import SearchForm from './SearchForm';
import { withRouter } from 'react-router';
import { getFirstDayOfTheMonth, getLastDayOfTheMonth, getDayAll, getMonthAll, getTime, getDate } from '../../../utils/action';
import AddForm from './AddForm';
import { withPermission } from '../../../components/withpermission'
const DownLoadButton = withPermission(Button, 'download')


const { TabPane } = Tabs
class productionLayoutList extends Component {
  state = {
    dataSource: [],
    advanced: false,
    nowDate: getDate(),
    nowDateTime: getTime(),
    searchItem: {
      startTime: getFirstDayOfTheMonth(),
      endTime: getDate(),
      department: localStorage.getItem('workShop')
    },
    workStatusList: [
      { id: 0, value: '未申请入库' },
      { id: 1, value: '已申请入库' },
    ],
    stateList: [],
    columns: [],
    activeKey: '0',
    visible: false,
    loading: false,
    addFrom: [],  // 车间数据
  };
  componentDidMount() {
    this.init()
    this.setState({ stateList: workStatusList })
    if (this.props.location.data) {
      this.setState({ searchItem: this.props.location.data }, this.fetch)
    } else {
      this.fetch()
    }
  }
  componentWillUnmount() {
    this.setState = () => {
      return;
    };
  }
  // 初始化查询
  init = () => {
    // 派工班组查询
    ProductionOrderService.findGroupAll().then(res => {
      const addFrom = res.data.data
      // console.log(addFrom, '派工班组查询');
      this.setState({ addFrom });
    })
  }

  //初始化加载数据
  fetch = () => {
    this.setState({ loading: true })
    const { searchItem } = this.state
    // searchItem.userId = localStorage.getItem('userId')

    productionLayoutListService.findPlanAll(searchItem).then(res => {
      this.setState({ loading: false })
      if (res.data.code !== 200) {
        openModalMessage('warning', res.data.msg)
        return
      }
      let data = res.data.data

      this.getColumns(data)
    }).catch(err => {
      openModalMessage('error', err.message)
    })
  }
  // 拼接表格列
  getColumns = (data) => {
    let len = {}, dataSource = [], startMin = '', startTime = '', endTime = ''
    for (let item of data) {
      len[item.batchNo] = item.list.length
      dataSource.push(...item.list)
      for (let item1 of item.list) {
        // startTime为 null 时定义 start 为当前时间
        let start = item1.startTime ? getTime(item1.startTime) : this.state.nowDateTime
        // 获取最小开始日期
        if (startMin) {
          startMin = startMin - start > 0 ? start : startMin
        } else {
          startMin = start
        }
        // console.log(startMin, 'startMin');
      }
    }

    startTime = startMin
    endTime = this.state.nowDateTime

    let month = [], date = [], dateAll = []
    let startMonth = new Date(startTime).getMonth() + 1
    let endMonth = new Date(endTime).getMonth() + 1
    if (startMonth == endMonth) {
      month = [startMonth]
      date = [getDayAll(startTime, endTime)]
      dateAll = [...getDayAll(startTime, endTime)]
    } else {
      month = getMonthAll(startTime, endTime)

      console.log(startTime);
      console.log(getLastDayOfTheMonth(startTime));
      console.log(getDayAll(startTime, getTime(getLastDayOfTheMonth(startTime))));
      console.log(getFirstDayOfTheMonth(endTime));
      console.log(this.state.nowDateTime);
      console.log(getDayAll(getTime(getFirstDayOfTheMonth(endTime)), this.state.nowDateTime));

      date = [getDayAll(startTime, getTime(getLastDayOfTheMonth(startTime))), getDayAll(getTime(getFirstDayOfTheMonth(endTime)), this.state.nowDateTime)]
      dateAll = [...getDayAll(startTime, getTime(getLastDayOfTheMonth(startTime))), ...getDayAll(getTime(getFirstDayOfTheMonth(endTime)), this.state.nowDateTime)]
    }
    console.log(date, 'date')
    // console.log(dateAll, 'dateAll')
    // console.log(month, 'month');
    let children = []
    for (let i in month) {
      let dateChildren = []
      for (let da of date[i]) {
        let obj1 = {
          title: Number(da.split('-')[2]),
          dataIndex: da,
          key: da,
          width: 70,
          align: 'center'
        }
        dateChildren.push(obj1)
      }

      let obj = {
        title: month[i] + ' 月',
        children: dateChildren,
      }
      children.push(obj)
    }
    let oldText = ''
    let columns = [
      {
        title: '类别',
        width: 250,
        children: [
          {
            title: '子类别',
            width: 250,
            children: [
              {
                title: '批号',
                dataIndex: 'batchNo',
                key: 'batchNo',
                width: 150,
                sorter: (a, b) => compareString(a.batchNo, b.batchNo),
                render: (text, record, index) => {
                  const obj = {
                    children: text,
                    props: {},
                  };

                  if (index == 0) {
                    oldText = text
                    obj.props.rowSpan = len[text];
                  } else if (oldText != text) {
                    oldText = text
                    obj.props.rowSpan = len[text];
                  } else {
                    obj.props.rowSpan = 0;
                  }
                  return obj;
                },
              },
              {
                title: '工序',
                dataIndex: 'procedureCode',
                key: 'procedureCode',
                width: 100,
              },
            ],
          },
        ],
      },
      {
        title: '进度',
        children,
      },
      {
        title: '',
        render: (text, record, index) => {
          // console.log(record)

          let a = this.state.stateList.find(item => item.id == record.isStates)

          let vstart = record.startTime ? record.startTime.split(' ')[0] : this.state.nowDate
          let vend = record.endTime ? record.endTime.split(' ')[0] : this.state.nowDate

          let startIndex = dateAll.findIndex(item => item == vstart)
          let endIndex = dateAll.findIndex(item => item == vend)

          // console.log(startIndex, endIndex)

          let top = 165 + 54 * index
          let left = 250 + startIndex * 70
          let width = (endIndex - startIndex + 1) * 70

          let content = (
            <div style={{ fontWeight: 'bold' }}>
              <p>{record.batchNo}</p>
              <p>
                <span>装配班组：{record.isStates == 0 && record.groupName == null ? '未指派' : record.groupName}</span><br />
                <span>装配开始：{record.startTime ? record.startTime : '--'}</span><br />
                <span>装配报工：{record.endTime ? record.endTime : '--'}</span>
              </p>
            </div>
          )

          let style = {
            position: 'absolute', left: left, top: top, backgroundColor: a.color ? a.color : 'pink',
            width: width, height: 50, lineHeight: '50px', textAlign: 'center', textOverflow: 'ellipsis',
            overflow: 'hidden', whiteSpace: 'nowrap'
          }
          return <Popover
            content={content}
            title={false}
            trigger="click"   // hover | click | focus
            mouseLeaveDelay={0}
          >
            <div style={style}>
              {
                //  && record.groupName == null
                record.isStates == 0 ?
                  <div title='未指派'>未指派</div> :
                  record.isStates == 1 ?
                    <div title='未开始'>未开始</div> :
                    record.startTime && record.isStates == 2 ?
                      <div style={{ display: 'flex', justifyContent: 'space-between', padding: '0 5px' }} title='装配开始 进行中'>
                        <div>装配开始</div>&emsp; {/* 装配开始 */}
                        <div>进行中</div>
                      </div> :
                      record.startTime && record.isStates == 3 ?
                        width < 100 ?
                          <div>开始-报工</div> :
                          <div style={{ display: 'flex', justifyContent: 'space-between', padding: '0 5px' }} title='装配开始 装配报工'>
                            <div>装配开始</div>&emsp; {/* 装配开始 */}
                            <div>装配报工</div> {/* 装配报工 */}
                          </div>
                        : null
              }
            </div>
          </Popover>
        }
      },
    ]

    this.setState({ dataSource, columns })
  }

  handleCancel = e => {
    this.setState({
      btnLoading: false
    });
    this.fetch();
  };


  onHandleAdvanced = () => {
    this.setState({ advanced: !this.state.advanced })
  }

  handleSearch = value => {
    console.log(value)
    if (value.rangeTime && value.rangeTime.length === 2) {
      value.startTime = value.rangeTime[0].format('YYYY-MM-DD 00:00:00')
      value.endTime = value.rangeTime[1].format('YYYY-MM-DD 23:59:59')
      delete (value.rangeTime)
    }
    this.setState({ searchItem: value }, this.fetch);
  };

  // 高级排序
  advancedSort = () => {
    this.setState({ visible: true })
  }

  downloadFather = () => {
    openModalMessage('功能待开发')
  }

  onChangeTabs = activeKey => {
    this.setState({ activeKey });
  };

  handleOk = () => {
    openModalMessage('功能待开发')
  }
  resetForm = () => {
    this.formSearch && this.formSearch.resetFields();
    this.setState({
      searchItem: {
        startTime: getFirstDayOfTheMonth(),
        endTime: getDate(),
        department: localStorage.getItem('workShop')
      }
    }, this.fetch);
  }
  render() {
    const { addFrom, loading, dataSource, advanced, workStatusList, searchItem, downloadLoading, visible, columns, stateList, nowDate } = this.state;

    return (
      <div>
        <BasicLayoutSearch>
          <SearchForm onSearch={this.handleSearch}
            onClick={this.onHandleAdvanced}
            advanced={advanced}
            searchItem={searchItem}
            workStatusList={workStatusList}
            addFrom={addFrom}
            resetForm={this.resetForm}
            ref={node => (this.formSearch = node)}
          />
        </BasicLayoutSearch>
        <Tabs tabBarExtraContent={(
          <div className='mydiv'>
            {[
              <DownLoadButton key='4' onClick={this.downloadFather} icon="download" loading={downloadLoading} />
              // <Button key={1} type="primary" onClick={() => this.advancedSort()} icon="sort-ascending">高级排序</Button>,
              // <Button type="primary" key={2} onClick={this.downloadFather} icon="download" loading={downloadLoading}>导出</Button>,
            ]}
          </div>
        )}
          hideAdd
          className="layout-model"
          onChange={this.onChangeTabs}
          activeKey={this.state.activeKey}
          type="card">
          <TabPane tab={'生产排班列表'} key="0">
            <Alert message={<div style={{ display: 'flex' }}>
              <div>说明：当天为 {nowDate}</div>
              {/* <div style={{ paddingLeft: 40 }}>
                {
                  stateList.map(item => {
                    return <Tag color={item.color}><span style={{ color: '#000000a6' }}>{item.value}</span></Tag>
                  })
                }
              </div> */}
            </div>} type="info" showIcon style={{ marginBottom: 15 }} />
            <Table
              loading={loading}
              style={{ position: 'relative', overflow: 'auto', width: '100%' }}
              columns={columns}
              dataSource={dataSource}
              rowKey={(record) => record.batchNo + '_' + record.procedureCode}
              bordered
              pagination={false}
            >
            </Table>
          </TabPane>

          {/* <TabPane tab={'统计图表'} key="1">
            统计图表
            <Details
              dataSource={dataSource}
              searchItem={searchItem}
            />
          </TabPane> */}
        </Tabs>

        <Modal
          title='高级排序'
          visible={visible}
          onCancel={() => this.setState({ visible: false })}
          onOk={this.handleOk}
        >
          <AddForm
            dataSource={dataSource}
          />
        </Modal>
      </div>
    );
  }
}
export default Form.create()(withRouter(productionLayoutList));